﻿using System;
using System.Collections.Generic;

namespace Bingosoft.Modules.SecurityConsole.Common.Helper
{
    public class DictionaryHelper
    {
        //获取根据key值从Dictionary中字符串类型的value
        public static string GetParamString(IDictionary<string, object> dictionary, string key)
        {
            if (dictionary.ContainsKey(key))
            {
                return dictionary[key] == Convert.DBNull ? null : Convert.ToString(dictionary[key]);
            }

            return null;
        }

        //获取根据key值从Dictionary中字符串类型的value
        public static int GetParamInt(IDictionary<string, object> dictionary, string key)
        {
            if (dictionary.ContainsKey(key))
            {
                return Convert.ToInt32(dictionary[key]);
            }

            return -1;
        }

        //获取根据key值从Dictionary中字符串类型的value
        public static object GetValueFromDictionary(IDictionary<string, object> dictionary, string key)
        {
            if (dictionary.ContainsKey(key))
            {
                return dictionary[key];
            }

            return null;
        }

        public static IDictionary<string,object> ConvertJsonStringToDictionary(string jsonString)
        {
            IDictionary<string, object> dictionary = new Dictionary<string, object>();
            if (string.IsNullOrEmpty(jsonString))
            {
                return dictionary;
            }

            jsonString = jsonString.Replace("{","").Replace("}","").Replace("'","");
            
            string[] properties = jsonString.Split(',');
            foreach (string property in properties)
            {
                string[] strs = property.Split(':');
                if(!dictionary.ContainsKey(strs[0]))
                {
                    dictionary.Add(strs[0], strs[1]);
                }
            }

            return dictionary;
        }
    }
}
